<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>回调 ref</title>
</head>
<body>
  <div id="root"></div>
  <script src="../js/react.development.js"></script>
  <script src="../js/react-dom.development.js"></script>
  <script src="../js/babel.min.js"></script>
  <script type="text/babel">
    class MyComponent extends React.Component {

      onBtnClick = (e) => {
        console.log(this)
        // 将 ref 回调函数中的参数赋值给一个本地变量，就可以通过此变量来获取到想要获取的元素
        console.log(this.currentNode)
      }

      render() {
        return (
          <div>
            {/* 第一步：添加 ref 属性，且属性值是一个回调函数，回调函数的参数就是想要获取的元素 */}
            <input type="text" placeholder="请输入值" ref={(currentNode) => this.currentNode = currentNode} />
            <button onClick={this.onBtnClick}>点击获取左侧输入框的值</button>
          </div>
        )
      }
    }
    ReactDOM.render(<MyComponent />, document.getElementById('root'))
  </script>
  



  <!-- 将 ref 写成内联函数的问题：更新时会执行两次 -->
  <div id="root01"></div>
  <script type="text/babel">
    class Demo extends React.Component {
      state = {
        count: 0
      }
      onBtnClick = () => {
        const { count } = this.state
        console.log('count: ', count)
        this.setState({
          count: count+1
        })
      }

      render() {
        console.log('执行 render 函数了')
        return (
          <div>
            <input type="text" placeholder="请输入值" ref={(curNode) => {this.currentNode = curNode; console.log('执行了ref内联回调函数:', curNode)}}/>
            <button onClick={this.onBtnClick}>更新状态: {this.state.count}</button>
          </div>
        )
      }
    }
    ReactDOM.render(<Demo />, document.getElementById('root01'))
  </script>



  <!-- 将回调函数写成 class 绑定的函数 -->
  <div id="root02"></div>
  <script type="text/babel">
    class Demo01 extends React.Component {
      state = {
        count: 0
      }

      onBtnClick = (e) => {
        const { count } = this.state
        console.log('更新前count: ', count, this.currentNode, this.currentNode.value)
        this.setState({
          count: count+1
        })
      }

      inputRefCb = (curNode) => {
        console.log('inputRefCb: ', curNode)
        this.currentNode = curNode
      }

      render() {
        const { count } = this.state
        return (
          <div>
            <input type="text" placeholder="请输入值" ref={this.inputRefCb} value={this.state.count} readOnly/>
            <button onClick={this.onBtnClick}>更新 count: {count}</button>
          </div>
        )
      }
    }
    ReactDOM.render(<Demo01 />, document.getElementById('root02'))
  </script>
</body>
</html>